import React, { useState, useRef, useEffect } from "react";
import mainSplashJPG from "@/assets/mainSplash_pc_2.jpg";

import styles from "./index.module.less";

interface CarouselProps {
  autoPlayInterval?: number;
}

const images = [mainSplashJPG, mainSplashJPG, mainSplashJPG];

const Carousel: React.FC<CarouselProps> = ({ autoPlayInterval = 4000 }) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [translateX, setTranslateX] = useState(0);
  const containerRef = useRef<HTMLDivElement>(null);

  const extendedImages = [...images, images[0]];

  const handleNext = () => {
    setCurrentIndex((prev) => {
      if (prev === images.length - 1) {
        // When reaching the last original image, quickly reset to first
        requestAnimationFrame(() => {
          if (containerRef.current) {
            containerRef.current.style.transition = "none";
            setCurrentIndex(0);
            requestAnimationFrame(() => {
              if (containerRef.current) {
                containerRef.current.style.transition =
                  "transform 300ms ease-out";
              }
            });
          }
        });
        return prev + 1;
      }
      return prev + 1;
    });
  };

  const handlePrev = () => {
    setCurrentIndex((prev) => {
      if (prev === 0) {
        // When at first image and going back, quickly jump to clone
        requestAnimationFrame(() => {
          if (containerRef.current) {
            containerRef.current.style.transition = "none";
            setCurrentIndex(images.length - 1);
            requestAnimationFrame(() => {
              if (containerRef.current) {
                containerRef.current.style.transition =
                  "transform 300ms ease-out";
              }
            });
          }
        });
        return images.length;
      }
      return prev - 1;
    });
  };

  const handleDragStart = (e: React.MouseEvent | React.TouchEvent) => {
    setIsDragging(true);
    const clientX = "touches" in e ? e.touches[0].clientX : e.clientX;
    setStartX(clientX - translateX);
  };

  const handleDragMove = (e: React.MouseEvent | React.TouchEvent) => {
    if (!isDragging) return;
    e.preventDefault();
    const clientX = "touches" in e ? e.touches[0].clientX : e.clientX;
    const newTranslateX = clientX - startX;
    setTranslateX(newTranslateX);
  };

  const handleDragEnd = () => {
    if (!isDragging) return;
    setIsDragging(false);

    const threshold = window.innerWidth * 0.2;
    if (Math.abs(translateX) > threshold) {
      if (translateX > 0) {
        handlePrev();
      } else {
        handleNext();
      }
    }
    setTranslateX(0);
  };

  useEffect(() => {
    const interval = setInterval(() => {
      if (!isDragging) {
        handleNext();
      }
    }, autoPlayInterval);

    return () => clearInterval(interval);
  }, [isDragging, autoPlayInterval]);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleTransitionEnd = () => {
      if (currentIndex === images.length) {
        container.style.transition = "none";
        setCurrentIndex(0);
        requestAnimationFrame(() => {
          container.style.transition = "transform 300ms ease-out";
        });
      }
    };

    container.addEventListener("transitionend", handleTransitionEnd);
    return () =>
      container.removeEventListener("transitionend", handleTransitionEnd);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentIndex, images.length]);

  return (
    <div
      className={styles["carousel-body"]}
      // className="relative w-full max-w-4xl mx-auto overflow-hidden group"
    >
      <div
        ref={containerRef}
        className={styles["slide-body"]}
        // className="flex transition-transform duration-300 ease-out"
        style={{
          transform: `translateX(calc(-${
            currentIndex * 100
          }% + ${translateX}px))`,
        }}
        onMouseDown={handleDragStart}
        onMouseMove={handleDragMove}
        onMouseUp={handleDragEnd}
        onMouseLeave={handleDragEnd}
        onTouchStart={handleDragStart}
        onTouchMove={handleDragMove}
        onTouchEnd={handleDragEnd}
      >
        {extendedImages.map((image, index) => (
          <div
            key={index}
            className={styles["slide-item"]}
            // className="w-full flex-shrink-0"
            style={{ touchAction: "none" }}
          >
            <img
              src={image}
              alt={`Slide ${index + 1}`}
              className={styles["slide-item-img"]}
              // className="w-full h-[400px] object-cover"
              draggable="false"
            />
          </div>
        ))}
      </div>

      <div
        className={styles["dot-body"]}
        // className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2"
      >
        {images.map((_, index) => (
          <div
            key={index}
            onClick={() => setCurrentIndex(index)}
            className={`${styles["dot-item"]} ${
              currentIndex === index ? styles["dot-active"] : ""
            }`}
            // className={`w-2 h-2 rounded-full transition-all ${
            //   currentIndex === index ? "bg-white w-4" : "bg-white/50"
            // }`}
          />
        ))}
      </div>
    </div>
  );
};

export default Carousel;
